<?php
/**
 * Created by PhpStorm.
 * User: tommy
 * Date: 2018/6/12
 * Time: 9:55
 */

namespace backend\models;


use common\component\BaseModel;
use common\component\XxteaD;
use common\models\User;

class SignupForm extends BaseModel
{
    public $username;
    public $password;
    public $csrf_token;
    public $_user;

    public function rules()
    {
        return [
            ['username','required','message'=>'请输入手机号码/邮箱'],
            [['username'],'trim'],


            [['password'],'required','message'=>'密码不能为空'],
            [['password'],'string','min' => 6,"tooShort"=>"请输入6位以上密码"],
            ['password','validatePassword']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
        ];
    }

    /*
     * 重置密码
     */
    public function resetpwd() {
        $this->setScenario("reset");
        if (!$this->validate()) {
            return false;
        }
        if ($this->csrf_token) {
            $this->password = XxteaD::decrypt($this->password,$this->csrf_token);
        }
        if (preg_match(\Yii::$app->params["emailPattern"],$this->username)) {
            $field = "email";
        } elseif (preg_match(\Yii::$app->params["mobilePattern"],$this->username)) {
            $field = "mobile";
        } else {
            $field = "username";
        }
        $user = User::findOne([$field=>$this->username]);
        if (!$user) {
            $this->addError("username","帐号不存在!");
            return false;
        }
        $user->password = $this->password;
        if (!$user->save()) {
            $this->addError("username",$user->getErrorsToString());
            return false;
        }
        //注册成功后执行
        $this->afterSignup();
        return true;
    }
    public function validatePassword($attribute,$params) {
        if (!$this->hasErrors()){
            $user = $this->getUser();
            if ($user) {
                $this->addError($attribute,"用户名已存在");
            }
        }
    }
    public function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }
        return $this->_user;
    }

    public function signup() {
        if (!$this->validate()) {
            return false;
        }
        //解码
        if ($this->csrf_token) {
            $this->password = XxteaD::decrypt($this->password,$this->csrf_token);
        }
        $user = new \common\models\User();
        $user->username = $this->username;
        $user->password = $this->password;
        if (!$user->save()) {
            $this->addError("username",$user->getErrorsToString());
            return false;
        }
        return true;
    }


}
